package com.taobao.client.component.templete;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;

/**
 * a HTMLTemplatePanel using a template which can be loaded from other HTML as
 * the panel
 * 
 * <code>
 * 	HTMLTemplatePanel panel = new HTMLTemplatePanel("template.html", "$content$");
 * </code>
 * @author crane.ding
 * @version 1.0 2008-11-21
 * @see {@link HTMLTemplateBase}
 */
public class HTMLTemplatePanel extends HTMLTemplateBase {

	protected static String templatePath;
	protected String templateURL;
	protected String templateElementId;
	protected Element iframe;
	private int timeInterval;
	private int checkCounter = 0;

	protected boolean iframeLoadOk = false;
	
	static{
		try {
			HTMLTemplatePanel.templatePath = getTemplatePath();
		} catch (Exception e) {
			HTMLTemplatePanel.templatePath = "";
			e.printStackTrace();
		}
	}

	public HTMLTemplatePanel() {
		super();
	}

	public HTMLTemplatePanel(String templateURL, String templateElementId) {
		super();

		this.templateURL = HTMLTemplatePanel.templatePath + templateURL;
		this.templateElementId = templateElementId;

		// now try to load the template html in an iframe
		loadIframe(this.templateURL);
	}

	/**
	 * 清除模板的内容
	 * 
	 * @param message
	 */
	public void clearHTML(String message) {
		DOM.setInnerHTML(getElement(), message);
	}

	private void updatePrompt() {
		DOM.setInnerHTML(getElement(), loadingHTML);
	}

	/** called from JSNI method */
	@SuppressWarnings("unused")
	private void checkStatus() {
		checkCounter++;
		if (checkCounter % 10 == 0)
			updatePrompt();

		if (checkCounter > 600) { // 60s
			clearInterval(timeInterval);
			DOM.setInnerHTML(getElement(), "Loading " + templateURL
					+ " timeout");
			return;
		}

		boolean loaded = checkStatus0(iframe);

		if (loaded == false)
			loaded = isOnload;

		if (loaded) {
			iframeLoadOk = true;
			clearInterval(timeInterval);
			changeDiv();
		}
	}

	boolean isOnload = false;

	protected void changeDiv() {
		String html = getLoadedElement(iframe, templateElementId);
		if (html != null) {
			setTemplateContent(html);
		} else {
			DOM.setInnerHTML(getElement(), "no element " + templateElementId
					+ " defined in document");
		}
	}

	/**
	 * 页面重新装载html模板的elementId
	 */
	public void changeDiv(String elementId) {
		if (!iframeLoadOk) {
			templateElementId = elementId;
			return;
		}
		String html = getLoadedElement(iframe, elementId);
		if (html != null) {
			setTemplateContent(html);
		} else {
			DOM.setInnerHTML(getElement(), "no element " + elementId
					+ " defined in document");
		}
	}

	private void setTemplateContent(String html) {
		DOM.setInnerHTML(getElement(), html);
		findPageWidgets(getElement());
		beforeFlushChildren();
		flushChildren(getElement());
		afterTemplateLoaded();
	}

	protected String getLoadedElement(Element iframe, String elementId) {
		Element el = getLoadedElement0(iframe, elementId);
		return DOM.toString(el);
	}
	
	protected static native String getTemplatePath()/*-{
		var pathname = window.location.pathname;
		var num = pathname.indexOf("/");
		var str = "http://"+window.location.host+"/";
		var href = window.location.href;
		var sub = href.substring(str.length);
		
		if (sub.indexOf("/") >= 0) {
			var sub_sub = sub.substring(sub.indexOf("/") + 1);
			// There exits two '/' character.
			if (sub_sub.indexOf("/") >= 0) {
				return str + sub.substring(0, sub.indexOf("/") + 1);
			} else {
				return str;
			}
		} else {
			return str;
		}
	}-*/;
	/**修改htmltemplatepanel
	 * 		if(num!=-1){
			pathname = pathname.substring(num+1);
			if((num=pathname.indexOf("/"))!=-1){
				return str+pathname.substring(0,num+1);
			}
			else {
				return str+pathname;
			}
		}else {
			return "";
		}
	 */

	private native Element getLoadedElement0(Element iframe, String elementId) /*-{
		var doc = iframe.contentWindow.document;
		var el = doc.getElementById(elementId);
		return el;
	}-*/;

	private native void clearInterval(int id) /*-{
		$wnd.clearInterval(id);
	}-*/;

	private native boolean checkStatus0(Element iframe) /*-{
		var win = iframe.contentWindow;

		if(win.readyState == 4 && win.document && win.document.body)
			return true;
		return false;
	}-*/;

	protected native void loadIframe(String url) /*-{
		var iframe = $wnd.document.createElement("iframe");
		iframe.setAttribute("gwt-info", "loading " + url);
		this.@com.taobao.client.component.templete.HTMLTemplatePanel::iframe = iframe;
		iframe.style.border = '0px';
		iframe.style.width = '0px';
		iframe.style.height = '0px';
		if($wnd.ActiveXObject){	// IE, see example in gwt.js#injectFrames
			iframe.src = url;
		}
		if($wnd.document.body.firstChild){
			$wnd.document.body.insertBefore(iframe, $wnd.document.body.firstChild);
		}
		else {
			$wnd.document.body.appendChild(iframe);
		}
		var self = this;
		this.@com.taobao.client.component.templete.HTMLTemplatePanel::timeInterval = $wnd.setInterval(
			function(){
				self.@com.taobao.client.component.templete.HTMLTemplatePanel::checkStatus()();
			}, 100);
		if($wnd.ActionXObject) {
			return;
		}
		if(iframe.contentWindow){
			iframe.contentWindow.location.replace(url);
		}
		else {
			iframe.src = url;
		}
	}-*/;

	protected void onAttach() {
		super.onAttach();
	}
}
